package com.chen.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.chen.subject.common.entity.PageResult;
import com.chen.subject.common.enums.IsDeletedFlagEnum;
import com.chen.subject.common.util.IdWorkerUtil;
import com.chen.subject.common.util.LoginUtil;
import com.chen.subject.domain.convert.SubjectInfoConverter;
import com.chen.subject.domain.entity.SubjectCategoryBO;
import com.chen.subject.domain.entity.SubjectInfoBO;
import com.chen.subject.domain.entity.SubjectOptionBO;
import com.chen.subject.domain.handler.subject.SubjectTypeHandler;
import com.chen.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.chen.subject.domain.redis.RedisUtil;
import com.chen.subject.domain.service.SubjectInfoDomainService;
import com.chen.subject.domain.service.SubjectLikedDomainService;
import com.chen.subject.infra.basic.entity.SubjectInfo;
import com.chen.subject.infra.basic.entity.SubjectInfoEs;
import com.chen.subject.infra.basic.entity.SubjectLabel;
import com.chen.subject.infra.basic.entity.SubjectMapping;
import com.chen.subject.infra.basic.service.SubjectEsService;
import com.chen.subject.infra.basic.service.SubjectInfoService;
import com.chen.subject.infra.basic.service.SubjectLabelService;
import com.chen.subject.infra.basic.service.SubjectMappingService;
import com.chen.subject.infra.entity.UserInfo;
import com.chen.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserRpc userRpc;
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;
    private static final String RANK_KEY = "subject_rank";

    @Override
    public SubjectInfo queryById(Long id) {
        return null;
    }

    /**
     * 添加题目信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        //使用工厂+策略的模式
        //一个工厂 包含四种类型 ，根据传入的type自动映射选择处理
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE
                .convertBoToInfo(subjectInfoBO);
        //设置为未删除状态
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //添加题目信息
        subjectInfoService.insert(subjectInfo);
        //根据getSubjectType去判断插入的是什么（使用工厂+策略的模式）
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        //设置题目的id
        subjectInfoBO.setId(subjectInfo.getId());
        //添加题目
        handler.add(subjectInfoBO);
        //获取分类id集合
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        //获取标签id集合
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappings = new LinkedList<>();
        categoryIds.forEach(categoryId->{
            labelIds.forEach(labelId->{
                SubjectMapping subjectMapping = new SubjectMapping();
                //设置一些必要的信息
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                //状态
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                subjectMappings.add(subjectMapping);
            });
        });
        //题目信息插入到subjectMappings中
        subjectMappingService.batchInsert(subjectMappings);
        //题目信息同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        //雪花算法生成id
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("任子双");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //redis放入zadd计入排行榜
        //出题数量加1
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);
    }

    @Override
    public SubjectInfo update(SubjectInfoBO subjectInfoBo) {
        return null;
    }


    @Override
    public boolean delete(SubjectCategoryBO subjectCategoryBO) {
        return false;
    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        //设置PageNo
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        //设置PageSize
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        //计算页数
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        //查询数据总量
        int count = subjectInfoService.countByCondition(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId());
        if (count==0){
            return pageResult;
        }
        //分页查询
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId(),start,subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANCE.convertListInfoToBO(subjectInfoList);
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }
    /**
     * 查询题目信息
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        //通过subjectInfo的id查询出题目信息
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        //获取题目类型,通过题目类型去查询题目答案和选项
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        //题目答案或者选项（判断题查询是否正确）
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId().intValue());
        //将题目答案或者选项放入SubjectInfoBO进行返回
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);
        //通过SubjectMapping去获取labelName
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        //查询未删除的subjectMapping
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //通过题目id去查询对应的的标签id的集合
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        //通过stream流转换为Long类型的集合
        List<Long> labelIdList = mappingList.stream()
                .map(SubjectMapping::getLabelId)
                .collect(Collectors.toList());
        //通过label的集合去查询题目对应的labelName集合
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        //通过stream流将labelName转换为String类型的集合
        List<String> labelNameList = labelList.stream()
                .map(SubjectLabel::getLabelName)
                .collect(Collectors.toList());

        bo.setLabelName(labelNameList);
        //题目是否被当前用户点赞过
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(),LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        //下一题和上一题
        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        //分类id，分类必须一致
        Long categoryId = subjectInfoBO.getCategoryId();
        //标签id，标签也应该一致
        Long labelId = subjectInfoBO.getLabelId();
        //题目id
        Long subjectId = subjectInfoBO.getId();
        //如果为空，返回空
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        //获取下一题的id，1代表查下一题
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        //设置下一题id
        bo.setNextSubjectId(nextSubjectId);
        //上一题id
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        //设置上一题id
        bo.setLastSubjectId(lastSubjectId);
    }

    /**
     * 全文检索
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        //设置关键词
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        //查询
        return subjectEsService.querySubjectList(subjectInfoEs);
    }
    /**
     * 获取题目贡献榜
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach((rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;
    }

    /**
     * 获取题目贡献榜
     */
//    @Override
//    public List<SubjectInfoBO> getContributeList() {
//       List<SubjectInfo> subjectInfoList =  subjectInfoService.getContributeList();
//       if (CollectionUtils.isEmpty(subjectInfoList)){
//           return Collections.emptyList();
//       }
//       List<SubjectInfoBO> boList = new LinkedList<>();
//        subjectInfoList.forEach(subjectInfo -> {
//            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
//            subjectInfoBO.setSubjectCount(subjectInfo.getSubjectCount());
//            UserInfo userInfo = userRpc.getUserInfo(subjectInfo.getCreatedBy());
//            subjectInfoBO.setCreateUser(userInfo.getNickName());
//            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
//            boList.add(subjectInfoBO);
//        });
//        return boList;
//    }
}
